import { Matrix4 } from "./Matrix4";

/*
 * @Author: Snow
 * @Date: 2021-10-18 21:03:04
 * @Description: 矩阵栈
 */
export class MatrixStack{
    private stack:{}[];
    constructor(){
        this.stack = [];
        
        // 因为栈是空的，需要放入一个初始化矩阵
        this.restore();
    }

    // 抛出顶部的矩阵，重置为前一个矩阵
    public restore():void{
        this.stack.pop();
        if(this.stack.length < 1){
            this.stack.push(Matrix4.identity());
        }
    }

    // 将当前矩阵备份到栈中
    public save():void{
        this.stack.push(this.getCurrentMatrix());
    }

    // 获取当前矩阵（栈顶的矩阵）
    public getCurrentMatrix():number[]{
        return (this.stack[this.stack.length - 1] as []).slice();
    }

    // 设置当前矩阵
    public setCurrentMatrix(matrix:number[]):void{
        this.stack[this.stack.length - 1] = matrix;
        return null;
    }

    public translate(x:number,y:number,z?:number):void{
        if(z === undefined){
            z = 0;
        }
        let m = this.getCurrentMatrix();
        this.setCurrentMatrix(Matrix4.multiply(m,Matrix4.translation(x,y,z)));
    }

    public rotateZ(angleInRadians:number):void{
        let m = this.getCurrentMatrix();
        this.setCurrentMatrix(Matrix4.multiply(m,Matrix4.rotateZ(angleInRadians)));
    }

    public scale(x:number,y:number,z?:number):void{
        if(z === undefined){
            z = 1;
        }
        let m = this.getCurrentMatrix();
        this.setCurrentMatrix(Matrix4.multiply(m,Matrix4.scaling(x,y,z)));
    }

}